package zerous.taphero.util;

import java.io.*;

import java.util.*;
import android.content.*;

public class Profile {
	//h{i();i2()};
	public List<DataGroup> dataGroups = new ArrayList<DataGroup>();
	public Profile(String data) {
		if(!data.equals("")) readData(data);
	}
	
	public DataGroup getDataGroup(String name) {
		for(DataGroup n: dataGroups) {
			if (name.equals(n.name)) return n;
		}
		return null;
	}
	
	public String getDataSrc() {
		String dataSrc = "";
		for(DataGroup g : dataGroups) {
			dataSrc += g.name;
			dataSrc += "{";
			for (Data d:g.datas) {
				dataSrc += d.name + ":" + d.data +";";
			}
			dataSrc += "},";
		}
		return dataSrc;
	}

	private void readData(String data) {
		DataGroup group;
		String[] groups = data.split(",");
		for (String s: groups) {
			group = new DataGroup();
			String name = "";
			String datas = "";
			int start = 0;

			for(int i = 0;s.charAt(i) != '{';i++) {
				name += s.charAt(i);
			}

			start = name.length() + 1;
			
			group.name = name;

			for(int j = start;s.charAt(j) != '}';++j) {
				datas += s.charAt(j);
			}

			String[] datasGroup = datas.split(";");
			for(String d: datasGroup) {
				String v = "";
				String vname = "";
				String[] val = d.split(":");
				
				vname = val[0];
				v = val[1];
				if(v.contains(".")) {
					group.datas.add(new Data<Float>(vname, Float.valueOf(v)));
				} else if(v.contains("_")) {
					group.datas.add(new Data<String>(vname, v));
				}
				else 
					group.datas.add(new Data<Integer>(vname, Integer.valueOf(v)));
				
			}
			dataGroups.add(group);
		}
	}
	
	public void add(DataGroup g) {
		dataGroups.add(g);
	}
	
	public void remove(int pos) {
		dataGroups.remove(pos);
	}
	
	public void remove(String name) {
		for(DataGroup g : dataGroups) {
			if (name.equals(g.name)) {
				dataGroups.remove(g);
				return;
			}
		}
	}
	
	public static final class DataGroup {
		public String name;
		public List<Data> datas = new ArrayList<Data>();
		public DataGroup() {}
		
		public void putInt(String n, int num) {
			Data d = getData(n);
			if (d == null)
				datas.add(new Data<Integer>(n, num));
			else
				d.data = num;
		}
		
		public Data getData(String n) {
			for (Data d:datas) {
				if (n.equals(d.name)) {
					return d;
				}
			}
			return null;
		}
	}
	
	public static final class Data<T> {
		public String name;
		public T data;
		
		public Data(String name, T data) {
			this.name = name;
			this.data = data;
		}
	}
}
